package br.com.sigmah.domain.repository;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import br.com.sigmah.domain.entity.Curso;

public abstract class AbstractDataManager<T, ID extends Serializable> {

	private static final Logger logger = Logger
			.getLogger(AbstractDataManager.class);

	@PersistenceContext
	private EntityManager entityManager;

	private Class<T> entityClass;

	public AbstractDataManager(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Transactional
	public T persist(T entity) {
		this.entityManager.persist(entity);
		this.entityManager.flush();
		return entity;
	}



	@Transactional
	public Collection<T> persistAll(Collection<T> entities) {
		for (T object : entities) {
			this.entityManager.persist(object);
			this.entityManager.flush();
		}
		return entities;
	}

	@Transactional
	public void remove(T entity) {
		this.entityManager.remove(entity);
		this.entityManager.flush();

	}
	
	public List<T> getAll(){
		CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
		CriteriaQuery<T> cq = cb.createQuery(entityClass);
		Root<T> root = cq.from(entityClass);
		cq.select(root);
		TypedQuery<T>query = getEntityManager().createQuery(cq);
		List<T> list = query.getResultList();
		return list;
	}
	
	
	public EntityManager getEntityManager() {
		return entityManager;
	}

}
